package com.itheima.service;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpringSecurityUserService1 implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    //模拟数据库中的用户数据
    public   Map<String, User> map = new HashMap<>();
    public void init() {
        User user1 = new User();
        user1.setUsername("admin");
//        user1.setPassword("admin");//明文密码（没有加密）
        //这个就是使用我们的那个加密给密码进行加密运算,加密后长度为60位
        user1.setPassword(bCryptPasswordEncoder.encode("admin"));

        User user2 = new User();
        user2.setUsername("xiaoming");
//        user2.setPassword("1234");//明文密码（没有加密）
        user2.setPassword(bCryptPasswordEncoder.encode("1234"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        init();
        System.out.println(username);
        //根据用户名去数据库里面查询这个用户的信息,这里是模拟的数据库信息,用的静态代码块
        User user = map.get(username);
        if(user==null){
            //就是不存在,直接返回null,这样框架就会知道,不正确,从而重新登录
            return null;
        }else{
            //存在,我们就个这个用户授予权限和角色
            List<GrantedAuthority>list=new ArrayList<>();
            //这个是授予权限
            list.add(new SimpleGrantedAuthority("permission_a"));
            list.add(new SimpleGrantedAuthority("add"));
            //这个是授予角色
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            //这个是没有进行加密的代码
//            org.springframework.security.core.userdetails.User user1 = new org.springframework.security.core.userdetails.User(username,
//                    "{noop}" + user.getPassword(), list);
            //这个是进行加密的代码,即不能再写成{noop}这种明文方式了
            org.springframework.security.core.userdetails.User user1 = new org.springframework.security.core.userdetails.User(username,
                     user.getPassword(), list);
            return user1;
        }
    }
}
